<?php

Yii::import('application.social_login.*');
require 'facebook/facebook.php';
require 'config_social/fbconfig.php';
require_once 'google/Google_Client.php';
require_once 'google/contrib/Google_PlusService.php';
require_once 'google/contrib/Google_Oauth2Service.php';

class SiteController extends Controller {

    /**
     * Declares class-based actions.
     */
    public function actions() {
        return array(
// captcha action renders the CAPTCHA image displayed on the contact page
            'captcha' => array(
                'class' => 'CCaptchaAction',
                'backColor' => 0xFFFFFF,
            ),
            // page action renders "static" pages stored under 'protected/views/site/pages'
// They can be accessed via: index.php?r=site/page&view=FileName
            'page' => array(
                'class' => 'CViewAction',
            ),
        );
    }

    /**
     * This is the default 'index' action that is invoked
     * when an action is not explicitly requested by users.
     */
    public function actionteach() {
        $this->render('teach');
    }

    public function auto_login($user_email, $providerId, $type) {
        $returnUrl = Yii::app()->createAbsoluteUrl('/myskillhippo');
        $user = Users::model()->findByAttributes(array('username' => $user_email));
        Users::model()->updateByPk($user->id, array('password' => md5($user_email)));
        $identity = new UserIdentity($user_email, $user_email);
        $identity->authenticate();
        Yii::app()->user->login($identity);
        $_SESSION['id'] = Yii::app()->user->id;
        if (Yii::app()->user->id) {
            //ShoppingCartByUser::saveCartbyUser(Yii::app()->user->id);
            ShoppingCartByUser::putShoppingCart();
        }
        makeUploadDir($_SESSION['id']);
        $userDetails = Users::getFrontEndUser($_SESSION['id']);        
        if ($type=='fb') {
            $uploadeDir = getUploadDir() . getLoginUserId();
            $rfilename = $providerId . '.jpg';
            $uploadnewDirProfile = $uploadeDir . '/profile/';
            $uploadnewDirProfileThumb = $uploadeDir . '/profile/thumb/';
            $uploadnewDirProfileMiniThumb = $uploadeDir . '/profile/minithumb/';
            $uploadnewDirProfileMain = $uploadeDir . '/profile/432X324/';
            $uploadnewDirProfileImg = file_get_contents('https://graph.facebook.com/' . $providerId . '/picture?width=400&height=400');
            $file1 = $uploadnewDirProfile . $providerId . '.jpg';
            file_put_contents($file1, $uploadnewDirProfileImg);
            $uploadnewDirProfileThumbImg = file_get_contents('https://graph.facebook.com/' . $providerId . '/picture?width=' . USER_IMAGE_WIDTH . '&height=' . USER_IMAGE_HEIGHT);
            $file2 = $uploadnewDirProfileThumb . $providerId . '.jpg';
            file_put_contents($file2, $uploadnewDirProfileThumbImg);
            $uploadnewDirProfileMiniThumbImg = file_get_contents('https://graph.facebook.com/' . $providerId . '/picture?width=' . USER_IMAGE_THUMB_WIDTH . '&height=' . USER_IMAGE_THUMB_HEIGHT);
            $file3 = $uploadnewDirProfileMiniThumb . $providerId . '.jpg';
            file_put_contents($file3, $uploadnewDirProfileMiniThumbImg);
            $uploadnewDirProfileMainImg = file_get_contents('https://graph.facebook.com/' . $providerId . '/picture?width=' . USER_IMAGE_PROFILE_WIDTH . '&height=' . USER_IMAGE_PROFILE_HEIGHT);
            $file4 = $uploadnewDirProfileMain . $providerId . '.jpg';
            file_put_contents($file4, $uploadnewDirProfileMainImg);
            Profiles::model()->updateByPk($userDetails->profile_id, array("photo" => $rfilename));
        }

        if (!empty(Yii::app()->session['class_course_review'])) {
            $returnUrl = Reviews::saveReviewAfterloginuser();
        }
        if (!empty(Yii::app()->session['trainer_profile_review'])) {
            $returnUrl = TrainerProfileReview::savetrainerReviewAfterloginuser();
        }
        if (!empty(Yii::app()->session['make_query'])) {
            $returnUrl = MakeQuery::makequeryafterloginuser();
        }
        if (!empty(Yii::app()->session['trainer_follower'])) {
            $returnUrl = TrainerFollow::saveTrainerfollowersafterlogin();
        }
        if (!empty(Yii::app()->session['shopping_cart_session'])) {
            $returnUrl = Yii::app()->createAbsoluteUrl('ShoppingCart/skillshopping');
        }
        $this->redirect($returnUrl);
    }

    public function actionIndex() {
        $this->pageTitle = HOME_PAGE_TITLE;
        $profile = new Profiles;
        $userModel = new Users();
        if (isset($_GET['oauth_provider'])) {
            $oauth_provider = $_GET['oauth_provider'];
            if ($oauth_provider == 'facebook') {
                $facebook = new Facebook(array(
                            'appId' => '1433437273566460',
                            'secret' => '836315ea0d8c4a88df00fb8a102779bd',
                        ));
                $user = $facebook->getUser();
                if (!empty($user)) {
                    $user_profile = $facebook->api('/me');
                    $haModel = HaLogins::model()->findByAttributes(array('login_provider_identifier' => $user_profile['email']));
                    if (empty($haModel)) {
                        HaLogins::saveUser($user_profile['id'], $user_profile['email'], $oauth_provider);
                    }
                    $checkdata = $userModel->findByAttributes(array('username' => $user_profile['email']));
                    if (empty($checkdata)) {
                        $userModel->activationKey = guid() . microtime();
                        $userModel->createtime = time();
                        $userModel->issubscribe = SkillConfig::STATUS_DEACTIVE;
                        $userModel->superuser = SkillConfig::STATUS_DEACTIVE;
                        $userModel->is_users = SkillConfig::STATUS_ACTIVE;
                        $userModel->status = SkillConfig::STATUS_ACTIVE;
                        $userModel->username = $user_profile['email'];
                        $userModel->password = md5($user_profile['email']);
                        if ($userModel->save(false)) {
                            $userRole = new UserHasRole();
                            $userRole->setAttribute('role_id', SkillConfig::WEB_USER);
                            $userRole->setAttribute('user_id', $userModel->id);
                            $userRole->save(false);
                            $profile = new Profiles();
                            $profile->first_name = $user_profile['first_name'];
                            $profile->last_name = $user_profile['last_name'];
                            $profile->facebook = $user_profile['link'];
                            $profile->termcondition = SkillConfig::STATUS_ACTIVE;
                            $profile->user_id = $userModel->id;
                            $profile->save();
                            $this->auto_login($user_profile['email'], $user_profile['id'], 'fb');
                        }
                    } else if ($checkdata->status == SkillConfig::STATUS_ACTIVE) {
                        $userModel->updateByPk($checkdata->id, array('status' => SkillConfig::STATUS_ACTIVE, 'lastvisit' => time()));
                        $this->auto_login($user_profile['email'], $user_profile['id'], 'fb');
                    }
                } else {
                    $login_url = $facebook->getLoginUrl(array('scope' => 'email'));
                    header("Location: " . $login_url);
                }
            }
        }

        $client = new Google_Client();

        $client->setApplicationName("skillhippologin");
        $client->setScopes(array('https://www.googleapis.com/auth/userinfo.email', 'https://www.googleapis.com/auth/plus.me'));
        $client->setClientId('1082743347334-t1uap07vq1kvca2e4q3m9de52l28qsrt.apps.googleusercontent.com');
        $client->setClientSecret('zijwQ7uFleDVUxk8hTWFkwOW');
        $client->setRedirectUri('http://skillhippo.com/site/index');
        $client->setDeveloperKey('1082743347334-4m9ik2t4kv8fuj5fg3pfpun4eve4c0cj.apps.googleusercontent.com');
        $plus = new Google_PlusService($client);
        $oauth2 = new Google_Oauth2Service($client);
        $authUrlGoogle = $client->createAuthUrl(); //echo  $authUrlGoogle;die;
        if (isset($_GET['code']) && !isset($_GET['oauth_provider'])) {
            $client->authenticate();
            $_SESSION['access_token'] = $client->getAccessToken();
            if ($client->getAccessToken()) {
                $guser = $oauth2->userinfo->get();
                $me = $plus->people->get('me');
                $haModel = HaLogins::model()->findByAttributes(array('login_provider_identifier' => $guser['email']));
                if (empty($haModel)) {
                    HaLogins::saveUser($me['id'], $guser['email'], 'google');
                }
                $checkdata = $userModel->findByAttributes(array('username' => $guser['email']));
                if (empty($checkdata)) {
                    $userModel->activationKey = guid() . microtime();
                    $userModel->createtime = time();
                    $userModel->issubscribe = SkillConfig::STATUS_DEACTIVE;
                    $userModel->superuser = SkillConfig::STATUS_DEACTIVE;
                    $userModel->is_users = SkillConfig::STATUS_ACTIVE;
                    $userModel->status = SkillConfig::STATUS_ACTIVE;
                    $userModel->username = $guser['email'];
                    $userModel->password = md5($guser['email']);
                    if ($userModel->save(false)) {
                        $userRole = new UserHasRole();
                        $userRole->setAttribute('role_id', SkillConfig::WEB_USER);
                        $userRole->setAttribute('user_id', $userModel->id);
                        $userRole->save(false);
                        $profile = new Profiles();
                        $profile->first_name = $me['name']['givenName'];
                        $profile->last_name = $me['name']['familyName'];
                        $profile->others = 'Google Link';
                        $profile->others_link = $me['url'];
                        $profile->termcondition = SkillConfig::STATUS_ACTIVE;
                        $profile->user_id = $userModel->id;
                        $profile->save();
                        $this->auto_login($guser['email'], '', 'gmail');
                    }
                } else if ($checkdata->status == SkillConfig::STATUS_ACTIVE) {
                    $userModel->updateByPk($checkdata->id, array('status' => SkillConfig::STATUS_ACTIVE, 'lastvisit' => time()));
                    $this->auto_login($guser['email'], '', 'gmail');
                }
            }
        }
        $cs = Yii::app()->clientScript;
        $cs->scriptMap = array('jquery-1.11.0.min.js' => false,);
        $date = date('Y-m-d');
        $leadArray = array('type' => 'workshop');
        $curatedArray = array('type' => 'curatedclasses');
        $homeCuretedarray = array();        
        $coursesArray = runningCourseHomepage(); 
        $coursedataProvider = new CArrayDataProvider($coursesArray, array(
                    'sort' => array(
                        'attributes' => array(
                            'start_date',
                        ),
                    ),
                ));

    
        $classWorkShoparray = workshoponHomePage($leadArray);       
        $classWorkShopdataProvider = new CArrayDataProvider($classWorkShoparray, array(
                    'sort' => array(
                        'attributes' => array(
                            'start_date',
                        ),
                    ),
                ));
        
        $classCuretedarray = workshoponHomePage($curatedArray);      
        $classCureteddataProvider = new CArrayDataProvider($classCuretedarray, array(
                    'sort' => array(
                        'attributes' => array(
                            'start_date',
                        ),
                    ),
                ));
        $this->render('index', array('coursedataProvider' => $coursedataProvider,
            'classCureteddataProvider' => $classCureteddataProvider,
            'classWorkShopdataProvider' => $classWorkShopdataProvider, 'classCuretedarray' => $classCuretedarray
        ));
    }

    /**
     * This is the action to handle external exceptions.
     */
    public function actionError() {
        $this->layout = 'errorlayout';
        if ($error = Yii::app()->errorHandler->error) {
            if (Yii::app()->request->isAjaxRequest)
                echo $error['message'];
            else
                $this->render('error', $error);
        }
    }

    public function actionsitemap() {
        $this->render('_site_map');
    }

    /**
     * Displays the contact page
     */
    public function actionContact() {
        $model = new Contactus;
        if (isset($_POST['Contactus'])) {
            $model->attributes = $_POST['Contactus'];
            $model->setAttribute('created', SkillConfig::CreateDateTime());
            if ($model->validate()) {
                $model->save(FALSE);
                $headers = "From: {$model->email}\r\nReply-To: {$model->email}";
                mail(Yii::app()->params['adminEmail'], $model->subject, $model->message, $headers);
                Yii::app()->user->setFlash('contact', 'Thank you for contacting us. We will respond to you as soon as possible.');
                echo CJSON::encode(array(
                    'status' => 'success'
                ));
                Yii::app()->end();
            } else {
                $error = CActiveForm::validate($model);
                if ($error != '[]')
                    echo $error;
                Yii::app()->end();
            }
        }
        $this->render('contact', array('model' => $model));
    }

    /**
     * Displays the login page
     */
    public function actionUserlogin() {
        $this->layout = false;
        $model = new LoginForm;
        $returnUrl = Yii::app()->createAbsoluteUrl('/myskillhippo');
        if (isset($_POST['LoginForm'])) {
            $model->attributes = $_POST['LoginForm'];
            if ($model->validate()) {
                if ($model->login()) {
                    $lastVisit = Users::model()->findByPk(Yii::app()->user->id);
                    $lastVisit->setAttribute('lastvisit', time());
                    $lastVisit->save();
                    if (!empty(Yii::app()->session['class_course_review'])) {
                        $returnUrl = Reviews::saveReviewAfterloginuser();
                    }
                    if (!empty(Yii::app()->session['trainer_profile_review'])) {
                        $returnUrl = TrainerProfileReview::savetrainerReviewAfterloginuser();
                    }
                    if (!empty(Yii::app()->session['make_query'])) {
                        $returnUrl = MakeQuery::makequeryafterloginuser();
                    }
                    if (!empty(Yii::app()->session['trainer_follower'])) {
                        $returnUrl = TrainerFollow::saveTrainerfollowersafterlogin();
                    }
                    if (!empty(Yii::app()->session['shopping_cart_session'])) {
                        $returnUrl = Yii::app()->createAbsoluteUrl('shoppingCart/skillshopping');
                    }
                    ShoppingCartByUser::putShoppingCart();
                    echo CJSON::encode(array(
                        'authenticated' => true,
                        'redirectUrl' => $returnUrl
                    ));

                    die;
                } else {
                    echo CJSON::encode($model->errors);
                    Yii::app()->end();
                }
            } else {
                $error = CActiveForm::validate($model);
                if ($error != '[]')
                    echo $error;
                Yii::app()->end();
            }
        }
// display the login form
//$this->render('//users/_userlogin-signup', array('model' => $model));
    }

    public function actionLogin() {
        $this->redirect(Yii::app()->homeUrl);
    }

    /**
     * Logs out the current user and redirect to homepage.
     */
    public function actionLogout() {
        if (Yii::app()->user->id) {
            ShoppingCartByUser::saveCartbyUser(Yii::app()->user->id);
        }
        Yii::app()->user->logout();
        $this->redirect(Yii::app()->homeUrl);
    }

}